package com.wx.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class SignUtil {

	private static String token = "helloworld";
	
	public static boolean checkSignature(String signature, String timetamp, String nonce) {
		String checktext = null;
		if(signature != null) {
			String[] paramArr = new String[] {token, timetamp, nonce};
			Arrays.sort(paramArr);
			
			StringBuffer content = new StringBuffer();
			for(int i = 0; i < paramArr.length; ++i) {
				content.append(paramArr[i]);
			}
			
			try {
				MessageDigest md = MessageDigest.getInstance("SHA-1");
			
				byte[] digest = md.digest(content.toString().getBytes());
				checktext = byteToStr(digest);
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return checktext !=null ? checktext.equals(signature.toUpperCase()) : false;
	}
	
	/**
     * 将字节数组转化我16进制字符串
     * @param byteArrays 字符数组
     * @return 字符串
     */
    private static String byteToStr(byte[] byteArrays){
        String str = "";
        for (int i = 0; i < byteArrays.length; i++) {
            str += byteToHexStr(byteArrays[i]);
        }
        return str;
    }

    /**
     *  将字节转化为十六进制字符串
     * @param myByte 字节
     * @return 字符串
     */
    private static String byteToHexStr(byte myByte) {
        char[] Digit = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        char[] tampArr = new char[2];
        tampArr[0] = Digit[(myByte >>> 4) & 0X0F];
        tampArr[1] = Digit[myByte & 0X0F];
        String str = new String(tampArr);
        return str;
    }

}
